home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8603 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.3 KB  |  64 lines

  1. Path: newshost.lanl.gov!tanmoy
  2. From: tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Problem Negating an Unsigned Char
  5. Date: 03 Mar 1996 05:21:31 GMT
  6. Organization: Los Alamos National Laboratory
  7. Message-ID: <TANMOY.96Mar2222131@qcd.lanl.gov>
  8. References: <Dnnros.Lq.0.-s@hkusuc.hku.hk>
  9. NNTP-Posting-Host: qcd.lanl.gov
  10. Mime-Version: 1.0
  11. Content-Type: text
  12. In-reply-to: h8716718@hkusua.hku.hk's message of Sat, 2 Mar 1996 21:00:27 GMT
  13.  
  14. In article <Dnnros.Lq.0.-s@hkusuc.hku.hk>
  15. h8716718@hkusua.hku.hk (Starry Hung) writes:
  16. <snip>
  17. SH: coding in a little bit redundant way (add a casting), however, I can't
  18. SH: convince myself why the language performs like this, should anybody
  19. SH: kindly tell me the story?
  20. <snip>
  21. SH: unsigned char a=0x11;
  22. SH: unsigned char b=0xEE;
  23. <snip>
  24. SH: void main( void ) {
  25.  
  26. Declaring main as returning void invokes undefined behaviour. This
  27. means that what the compiler does with your program cannot be
  28. explained according to the rules of the C language. I assume that you
  29. had actually written `int main(void) {' instead.
  30.  
  31. SH:     if( a == ~b ) {
  32.  
  33. The problem is that before the application of almost any arithmetic or
  34. bit manipulation operators, `integral promotions' take place. These
  35. change char and signed and unsigned char and short to either int ot
  36. unsigned int (depending on how big they are). So, the quantity that ~
  37. is complementing is not really a char: it is possibly an int (or
  38. unsigned int), say 0x00EE. The complement of this is then 0xFF11.
  39.  
  40. On the other hand a is also promoted (before comparison), but to
  41. 0x0011. Hence the test fails.
  42.  
  43. SH:       c=1;
  44. SH:     }
  45. SH: }
  46. SH: 
  47. SH: The c remains unchange, while it changes to 1 if I cast the ~b to unsigned
  48. SH: char as if( a == (unsigned char) ~b )
  49.  
  50. In this case, the 0xFF11 (say) gets converted back to an unsigned char
  51. 0x11, and is then promoted to 0x0011 before comparison. 
  52.  
  53. Hope this helps.
  54.  
  55. Cheers
  56. Tanmoy
  57. --
  58. tanmoy@qcd.lanl.gov(128.165.23.46) DECNET: BETA::"tanmoy@lanl.gov"(1.218=1242)
  59. Tanmoy Bhattacharya O:T-8(MS B285)LANL,NM87545 H:#9,3000,Trinity Drive,NM87544
  60. Others see <gopher://yaleinfo.yale.edu:7700/00/Internet-People/internet-mail>,
  61. <http://alpha.acast.nova.edu/cgi-bin/inmgq.pl>or<ftp://csd4.csd.uwm.edu/pub/
  62. internetwork-mail-guide>. -- <http://nqcd.lanl.gov/people/tanmoy/tanmoy.html>
  63. fax: 1 (505) 665 3003   voice: 1 (505) 665 4733    [ Home: 1 (505) 662 5596 ]
  64.